import { Card, Form, Input, Select, Button, Table, Popover, Badge, Popconfirm, message, Modal } from "antd";
import TitleHandlerDiv from "../../../components/TableHandlerArea";
import React, { useState, useEffect } from "react";
import "./index.scss";
import { HeaderFormCom, PaginationCom } from "../../../components/ArticleDetailCom/DrawerMultilayer/OssFileDrawer";
import api from "../../../api";
import { useHistory } from "react-router-dom";
const { Option } = Select;
const { Column } = Table;

const CommentAdmin = () => {
  const history = useHistory();
  const [commentList, setCommentList] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);
  const [total, setTotal] = useState(0);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [replyValue, setReplyValue] = useState("");
  const [addInfo, setAddInfo] = useState({
    email: "",
    content: "",
    article_id: null,
    parent_content: "",
    parent_id: "",
    author: "",
  });
  const onSelectChange = (selectedRowKeys, selectedRows) => {
    setSelectedRows([...selectedRows]);
  };

  const rowSelection = {
    selectedRows,
    onChange: onSelectChange,
  };
  const [form, setForm] = useState({
    pageIndex: 1,
    pageSize: 8,
    author: "",
    state: "null",
    email: "",
  });
  useEffect(() => {
    init();
  }, []);
  const init = () => {
    getCommentList();
  };
  const showModal = (data) => {
    setAddInfo({
      email: data.email,
      author: JSON.parse(window.sessionStorage.getItem("userData")).username,
      parent_content: data.content,
      article_id: data.article_id,
      parent_id: data.id,
    });
    setIsModalVisible(true);
    setReplyValue("");
  };

  const handleOk = async () => {
    await api.addCommentList({
      ...addInfo,
      content: replyValue,
    });
    await init();
    await setIsModalVisible(false);
    message.success("回复成功");
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };
  //获取文章列表
  const getCommentList = async () => {
    const res = await api.getCommentList({ ...form });
    setCommentList([...res.data.res]);
    setTotal(res.data.total);
  };
  //select  change事件
  const handleChange = (value, type) => {
    form[type] = value;
    setForm({ ...form });
  };
  //form表单  change事件
  const changeFormValue = (value, type) => {
    form[type] = value;
    setForm({ ...form });
  };
  //重置表单
  const resetForm = () => {
    form.pageIndex = 1;
    form.pageSize = 8;
    form.author = "";
    form.state = "null";
    form.email = "";
    setForm({
      ...form,
    });
  };
  //删除(单个)
  const delCommentList = async (id) => {
    await api.delCommentList(id);
    await init();
    message.success("删除成功");
  };
  //跳转页面
  const goUrl = (path) => {
    history.push(path);
  };
  //批量操作函数   apiPath<string>  api下的函数名
  const batchHandlerList = async (apiPath) => {
    await api[apiPath]({ batchList: selectedRows });
    await getCommentList();
    message.success("操作成功");
  };
  //分页
  const changePagination = async (pageIndex, pageSize) => {
    form.pageIndex = pageIndex;
    form.pageSize = pageSize;
    await setForm({ ...form });
    getCommentList();
  };
  const auditComment = async (id, bool) => {
    if (bool) {
      await api.passComment({ id: id });
    } else {
      await api.refuseComment({ id: id });
    }
    await init();
    message.success("操作成功");
  };
  return (
    <div className="all-article">
      <Card>
        <HeaderFormCom handlerResetBtn={resetForm} handlerSearchBtn={getCommentList}>
          <Form layout="inline">
            <Form.Item label="称呼">
              <Input placeholder="请输入称呼" value={form.author} onChange={(e) => changeFormValue(e.target.value, "author")} />
            </Form.Item>
            <Form.Item label="Email">
              <Input placeholder="请输入联系方式" value={form.email} onChange={(e) => changeFormValue(e.target.value, "email")} />
            </Form.Item>
            <Form.Item label="状态">
              <Select value={form.state === "null" ? null : form.state} style={{ width: 170 }} onChange={(e) => handleChange(e, "state")}>
                <Option value={1}>已通过</Option>
                <Option value={0}>未通过</Option>
              </Select>
            </Form.Item>
          </Form>
        </HeaderFormCom>
      </Card>
      <Card
        title={
          <TitleHandlerDiv showHandlerArea={selectedRows.length} handlerBtnClick={() => goUrl("/add/page")} isShowBtn={false}>
            <div className="article_handler_btn">
              <Button onClick={() => batchHandlerList("batchPassComments")}>通过</Button>
              <Button onClick={() => batchHandlerList("batchRefuseComments")}>拒绝</Button>
              <Button danger onClick={() => batchHandlerList("batchDelComments")}>
                删除
              </Button>
            </div>
          </TitleHandlerDiv>
        }
        className="table-card"
      >
        <Table
          rowSelection={{ type: "checkbox", ...rowSelection }}
          dataSource={commentList}
          rowKey="id"
          pagination={false}
          scroll={{ x: 1500 }}
          style={{ width: "100%", overflow: "none" }}
        >
          <Column
            title="状态"
            dataIndex="state"
            fixed="left"
            render={(text) => {
              return (
                <>
                  <Badge dot color={Number(text) ? "#52C41A" : "#F5222D"}></Badge>
                  {Number(text) ? "通过" : "未通过"}
                </>
              );
            }}
          />
          <Column title="称呼" dataIndex="author" width={200} />
          <Column title="联系方式" dataIndex="email" />
          <Column
            title="原始内容"
            dataIndex="content"
            render={(text) => {
              return (
                <Popover content={text} title="评论详情-原始内容">
                  <Button type="link">查看内容</Button>
                </Popover>
              );
            }}
          />
          <Column
            title="HTML内容"
            dataIndex="content"
            render={(text) => {
              return (
                <Popover content={text} title="评论详情-HTML 内容">
                  <Button type="link">查看内容</Button>
                </Popover>
              );
            }}
          />
          <Column title="管理文章" dataIndex="admin_article" />
          <Column title="创建时间" dataIndex="comment_time" align="center" width={200} />
          <Column
            title="父级评论"
            dataIndex="parent_content"
            align="center"
            render={(text) => {
              return text ? text : "无";
            }}
          />
          <Column
            width={280}
            title="操作"
            dataIndex="action"
            fixed="right"
            render={(_, record) => {
              return (
                <div>
                  <Button type="link" onClick={() => auditComment(record.id, true)}>
                    通过
                  </Button>
                  <Button type="link" onClick={() => auditComment(record.id, false)}>
                    拒绝
                  </Button>
                  <Button type="link" onClick={() => showModal(record)}>
                    回复
                  </Button>
                  <Popconfirm title="确认删除这个文章？" okText="确认" cancelText="取消" onConfirm={() => delCommentList(record.id)}>
                    <Button type="link">删除</Button>
                  </Popconfirm>
                </div>
              );
            }}
          />
        </Table>
        <div className="pagination-box">
          <PaginationCom total={total} onChange={changePagination} pageSize={form.pageSize} pageIndex={form.pageIndex} />
        </div>
      </Card>
      <ReplyModal visible={isModalVisible} handleOk={handleOk} handleCancel={handleCancel} title="回复评论" okText="回复">
        <Input.TextArea
          autoSize={{ minRows: 6, maxRows: 20 }}
          placeholder="支持Markdown"
          value={replyValue}
          onChange={(e) => setReplyValue(e.target.value)}
        ></Input.TextArea>
      </ReplyModal>
    </div>
  );
};

export default CommentAdmin;
//modal对话框
export const ReplyModal = ({ visible, handleOk, handleCancel, title = "Basic Modal", cancelText = "取消", okText = "确认", ...props }) => {
  return (
    <Modal title={title} visible={visible} onOk={handleOk} onCancel={handleCancel} cancelText={cancelText} okText={okText}>
      {props.children}
    </Modal>
  );
};
